/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.ufpe.cin.dmo4.middleware.client;

import br.ufpe.cin.dmo4.middleware.message.Marshaller;
import br.ufpe.cin.dmo4.middleware.message.RequestMessage;
import br.ufpe.cin.dmo4.middleware.message.ResponseMessage;
import br.ufpe.cin.dmo4.middleware.remotingerrors.RemotingError;

/**
 *
 * @author Danilo
 */
public class Requestor {
    private String invokerAddress;
    private ClientRequestHandler clientRequestHandler;
    private Marshaller marshaller;

    public Requestor(String invokerAddress, Marshaller marshaller) {
        this.invokerAddress = invokerAddress;
        this.clientRequestHandler = new ClientRequestHandler(invokerAddress);
        this.marshaller = marshaller;
    }
    
        
    public ResponseMessage invoke(RequestMessage invocation) throws RemotingError {
        byte[] bytesToSent = marshaller.marshall(invocation);
        
        byte[] receivedBytes = clientRequestHandler.send(bytesToSent);
        
        ResponseMessage response = null;
        
        try {
            response = marshaller.unmarshalResponse(receivedBytes);
        } catch (Exception e) {
            throw new RemotingError();
        }
        
        return response;
    }
}
